import DeptAPI from "@/api/system/dept-api";
import OrgAPI from "@/api/org/org";
import UserAPI from "@/api/system/user-api";
import { businessStatusMap, isNotMap } from "@/commonData/dict";
import { useTableData } from "@/components/SmTable/src/utils";
import { buildTree } from "@/utils/transform";

export const useTable = () => {
  const list: any = ref([]);
  const total = ref(0);
  const loading = ref(false);

  const { tableOptions, transformTableOptions } = useTableData();

  // 还有一个表单我之前应该写过可以引入
  const fieldMap = {
    organizationNo: "机构编码",

    organizationName: "机构名称",
    organizationShortName: "机构简称",
    province: "省",
    city: "市",
    district: "区",
    address: "地址",
    phone: "电话",
    areaCode: "区号",
    fax: "传真",
    establishDate: "成立日期",

    isLegalPerson: {
      label: "是否是法人机构",
      slot: "isLegalPerson",
      textMap: isNotMap,
    },
    hasSettlementQualification: {
      label: "是否有结算资格",
      slot: "hasSettlementQualification",
      textMap: isNotMap,
    },
    hasAmountViewPermission: {
      label: "可视实收金额权限",
      slot: "hasAmountViewPermission",
      textMap: isNotMap,
    },
    businessScope: "主营业务范围",
    businessStatus: {
      label: "业务状态",
      slot: "businessStatus",
      textMap: businessStatusMap,
    },

    remark: "备注",
    creator: "创建人",
    updater: "更新人",

    // createTime: "创建时间",

    operate: {
      label: "操作",
      slot: "operate",
      fixed: "right",
      width: "180px",
    },
  };
  tableOptions.value = transformTableOptions(fieldMap);

  const queryParams: any = reactive({
    pageNum: 1,
    pageSize: 10,
  });

  /** 查询列表 */
  const getList = async () => {
    loading.value = true;
    try {
      const data = await OrgAPI.getList(queryParams);
      data?.list?.forEach((item: any) => {
        item.value = item.id;
        item.label = item.organizationName;
      });
      const treeData = buildTree(data?.list);
      list.value = treeData;
      // total.value = data.total;
    } finally {
      loading.value = false;
    }
  };

  function handleQuery() {
    queryParams.pageNum = 1;
    getList();
  }

  const queryFormRef = ref();
  /** 添加/修改操作 */
  const formRef = ref();
  const openForm = (type: string, id?: number) => {
    formRef.value.open(type, id);
  };

  /** 重置按钮操作 */
  const handleResetQuery = () => {
    queryFormRef.value.resetFields();
    nextTick(() => {
      handleQuery();
    });
  };

  return {
    tableOptions,
    list,
    total,
    loading,
    queryParams,
    getList,
    handleQuery,
    handleResetQuery,
    queryFormRef,
    formRef,
    openForm,
  };
};
